#!/usr/bin/python2

import subprocess,re

# kill action: 0 -> power off, 1 -> save state
killAction = 1

# Only change anything below this comment if you know, what you're doing!!
print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<openbox_pipe_menu>")

killActions   = ['poweroff', 'savestate']
notRunningVms = []
runningVms    = []
vmNamePattern = re.compile('"(.+)" .*')
for vm in subprocess.check_output(['VBoxManage', 'list', 'vms']).decode("utf-8").split("\n"):
     match = vmNamePattern.match(vm)
     if match:
         notRunningVms.append(match.group(1))
for vm in subprocess.check_output(['VBoxManage', 'list', 'runningvms']).decode("utf-8").split("\n"):
     match = vmNamePattern.match(vm)
     if match:
         runningVms.append(match.group(1))
         notRunningVms.remove(match.group(1))

if len(notRunningVms):
     print("<separator label=\"Start VM\"/>")
     for vm in notRunningVms:
         print("<item label=\"" + vm + "\">")
         print("<action name=\"Execute\">")
         print("<execute>VBoxManage startvm \"" + vm + "\"</execute>")
         print("</action>\n</item>")
if len(runningVms):
     print("<separator label=\"Stop VM\"/>")
     for vm in runningVms:
         print("<item label=\"" + vm + "\">")
         print("<action name=\"Execute\">")
         print("<execute>VBoxManage controlvm \"" + vm + "\" " + killActions[killAction] + "</execute>")
         print("</action>\n</item>")

print("</openbox_pipe_menu>")